package com.wosai.teach.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.wosai.teach.R;
import com.wosai.teach.cst.C;
import com.wosai.teach.dialog.ChooseHeadDialog;
import com.wosai.teach.dto.JsonResult;
import com.wosai.teach.entity.User;
import com.wosai.teach.listener.ChooseHeadListener;
import com.wosai.teach.oss.OssCallBack;
import com.wosai.teach.oss.OssManager;
import com.wosai.teach.utils.BitmapHelp;
import com.wosai.teach.utils.OtherUtils;

/**
 * @author qiumy
 * @e-mail : qiumy@wosaitech.com
 * @date : 2015年9月6日 上午9:23:45
 * @desc : 展示修改信息(备份)
 */
@ContentView(R.layout.activity_information_bak)
public class InformationBakActivity extends AppActivity implements OssCallBack,
		OnCheckedChangeListener {

	@ViewInject(R.id.information_icon)
	private ImageView ifIcon;
	@ViewInject(R.id.information_code)
	private TextView ifCode;
	@ViewInject(R.id.information_username)
	private TextView ifUserName;
	@ViewInject(R.id.information_sex)
	private TextView ifSex;
	@ViewInject(R.id.information_class)
	private TextView ifClass;
	@ViewInject(R.id.information_email)
	private TextView ifEmail;
	@ViewInject(R.id.information_mobile)
	private TextView ifMobile;
	@ViewInject(R.id.information_microMsg)
	private TextView ifMicroMsg;
	@ViewInject(R.id.information_qq)
	private TextView ifQQ;
	@ViewInject(R.id.if_1)
	private LinearLayout if_1;
	@ViewInject(R.id.if_2)
	private LinearLayout if_2;
	@ViewInject(R.id.if_3)
	private LinearLayout if_3;
	@ViewInject(R.id.if_4)
	private LinearLayout if_4;
	@ViewInject(R.id.if_5)
	private LinearLayout if_5;
	@ViewInject(R.id.if_6)
	private LinearLayout if_6;
	@ViewInject(R.id.if_7)
	private LinearLayout if_7;
	@ViewInject(R.id.if_8)
	private LinearLayout if_8;

	private User user;
	private BitmapUtils bitmapUtils;
	private String sex = "male";
	private PopupWindow mPopupWindow;
	private List<LinearLayout> lLayout = new ArrayList<LinearLayout>();

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setmPageName("展示个人信息，可以进行个人信息的修改");
		setTopTitle(R.string.information);
		enableBack(true);
		initView();
	}

	private void initView() {
		bitmapUtils = BitmapHelp.getBitmapUtils(this);
		refresh();
		lLayout.add(if_1);
		lLayout.add(if_2);
		lLayout.add(if_3);
		lLayout.add(if_4);
		lLayout.add(if_5);
		lLayout.add(if_6);
		lLayout.add(if_7);
		lLayout.add(if_8);
	}

	@OnClick(value = { R.id.information_icon })
	public void information_icon(View v) {
		ChooseHeadDialog choose = new ChooseHeadDialog(this);
		choose.init(new ChooseHeadListener() {

			@Override
			public void onNative() {
				Intent intentFromGallery = new Intent();
				intentFromGallery.setType("image/*"); // 设置文件类型
				intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(intentFromGallery,
						C.PHOTO_REQUEST_GALLERY);
			}

			@Override
			public void onPhoto() {
				// 判断存储卡是否可以用，可用进行存储
				if (OtherUtils.hasSdcard()) {
					Intent intentFromCapture = new Intent(
							MediaStore.ACTION_IMAGE_CAPTURE);
					intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri
							.fromFile(new File(Environment
									.getExternalStorageDirectory(),
									C.IMAGE_FILE_NAME)));
					startActivityForResult(intentFromCapture,
							C.PHOTO_REQUEST_CAMERA);
				} else {
					toastShow("存储卡不可用");
				}
			}
		});
		choose.show();
	}

	// R.id.information_nickname,R.id.information_username,R.id.information_sex,R.id.information_class,
	@OnClick(value = { R.id.information_email, R.id.information_mobile,
			R.id.information_microMsg, R.id.information_qq })
	public void information_nickname(View v) {
		getPopupWindowInstance(v.getId());
		informationChangeShow(v.getId(), true);
		mPopupWindow.showAsDropDown(if_1);
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		mPopupWindow.dismiss();
		ifVisible(7, false);
	}

	/**
	 * 获取PopupWindow实例
	 * 
	 * @param vId
	 */
	private void getPopupWindowInstance(int vId) {
		if (null != mPopupWindow && mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
			ifVisible(7, false);
		} else {
			initPopuptWindow(vId);
			openKeyboard(new Handler(), 500);
		}
	}

	/**
	 * 创建PopupWindow
	 * 
	 * @param vId
	 */
	private void initPopuptWindow(final int vId) {
		LayoutInflater layoutInflater = LayoutInflater.from(this);
		View contentView = layoutInflater.inflate(
				R.layout.activity_information_popupwindow, null);
		// 创建一个弹出框
		mPopupWindow = new PopupWindow(contentView, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		mPopupWindow.setFocusable(true); // 设置PopupWindow可获得焦点
		mPopupWindow.setContentView(contentView);
		// mPopupWindow.setOutsideTouchable(true);// 设置外部区域可触摸
		// mPopupWindow.setTouchable(true); //设置PopupWindow可触摸
		// popupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 设置触摸和按键，此处就是实现点击外部关闭弹出框
		contentView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (mPopupWindow.isShowing()) {
					mPopupWindow.dismiss();
					ifVisible(7, false);
				}
				return false;
			}
		});
		contentView.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if ((keyCode == KeyEvent.KEYCODE_MENU)
						&& (mPopupWindow.isShowing())) {
					mPopupWindow.dismiss();
					ifVisible(7, false);
					return true;
				}
				return false;
			}
		});

		final EditText editText = (EditText) contentView
				.findViewById(R.id.information_change_popedittext);
		RadioGroup changeSex = (RadioGroup) contentView
				.findViewById(R.id.information_change_sex);
		TextView popText = (TextView) contentView.findViewById(R.id.if_head);
		editText.setVisibility(View.VISIBLE);
		changeSex.setVisibility(View.GONE);
		popText.setText(null);
		editText.setText("");
		if (vId == R.id.information_code) {
			popText.setText(R.string.information_nickname);
			editText.setText(user.getNickName() + "");
			editText.setInputType(InputType.TYPE_CLASS_TEXT);
			editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
					10) });
		} else if (vId == R.id.information_username) {
			popText.setText(R.string.information_name);
			editText.setText(user.getUserName() + "");
			editText.setInputType(InputType.TYPE_CLASS_TEXT);
			editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
					5) });
		} else if (vId == R.id.information_sex) {
			popText.setText(R.string.information_sex);
			editText.setVisibility(View.GONE);

			changeSex.setVisibility(View.VISIBLE);
			final RadioButton sexMale = (RadioButton) contentView
					.findViewById(R.id.sex_male);
			final RadioButton sexFemale = (RadioButton) contentView
					.findViewById(R.id.sex_female);

			changeSex.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(RadioGroup group, int checkedId) {
					if (checkedId == sexFemale.getId()) {
						sex = "female";
					} else {
						sex = "male";
					}
				}
			});
		} else if (vId == R.id.information_class) {
			popText.setText(R.string.information_class);
			editText.setText(user.getClassId() + "");
			editText.setInputType(InputType.TYPE_CLASS_NUMBER);
			editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
					2) });
		} else if (vId == R.id.information_email) {
			popText.setText(R.string.information_email);
			editText.setText(user.getEmail() == null ? "" : user.getEmail());
			editText.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
			editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
					25) });
		} else if (vId == R.id.information_mobile) {
			popText.setText(R.string.information_mobile);
			editText.setText(user.getMobile() == null ? "" : user.getMobile());
			editText.setInputType(InputType.TYPE_CLASS_PHONE);
			editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
					11) });
		} else if (vId == R.id.information_microMsg) {
			popText.setText(R.string.information_microMsg);
			editText.setText(user.getMicroMsg() == null ? "" : user
					.getMicroMsg());
			editText.setInputType(InputType.TYPE_CLASS_TEXT);
			editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
					10) });
		} else if (vId == R.id.information_qq) {
			popText.setText(R.string.information_qq);
			editText.setText(user.getQQ() == null ? "" : user.getQQ());
			editText.setInputType(InputType.TYPE_CLASS_NUMBER);
			editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
					10) });
		} else {
			return;
		}
		if (vId != R.id.information_sex) {
			// 打开键盘，设置延时时长
			openKeyboard(new Handler(), 500);
		}

		Button btnOk = (Button) contentView.findViewById(R.id.button_OK);
		Button btnCancel = (Button) contentView
				.findViewById(R.id.button_cancel);
		btnCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mPopupWindow.dismiss();
				ifVisible(7, false);
			}
		});

		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				System.out.println(editText.getText());
				if (vId == R.id.information_class) {
					try {
						int iClass = Integer.parseInt(editText.getText()
								.toString());
						informationChange(vId, iClass);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else if (vId == R.id.information_sex) {
					informationChange(vId, sex);
				} else {
					informationChange(vId, editText.getText().toString());
				}
				mPopupWindow.dismiss();
				ifVisible(7, false);
			}
		});
	}

	private void informationChange(int vId, String string) {
		HttpUtils http = new HttpUtils();
		String url = C.HTTP_USER_INFO_UPDATE;
		RequestParams params = new RequestParams();
		url = url.replace("{userId}", user.getUserId() + "");

		User userChange = new User();
		userChange.setUserId(user.getUserId());

		if (vId == R.id.information_code) {
			if ((string.length() > 0) && (!string.trim().equals(""))) {
				userChange.setNickName(string);
			} else {
				toastShow("请输入1-10位非空字符");
				return;
			}

		} else if (vId == R.id.information_username) {
			if (OtherUtils.checkNameChese(string) && (string.length() > 1)) {
				userChange.setUserName(string);
			} else {
				toastShow("请输入2-5位中文字符");
				return;
			}

		} else if (vId == R.id.information_sex) {
			userChange.setSex(string);
			sex = "male";
		} else if (vId == R.id.information_email) {
			if (OtherUtils.isEmailValid(string)) {
				userChange.setEmail(string);
			} else if (OtherUtils.CheckNull(string)) {
				userChange.setEmail("");
			} else {
				toastShow("请输入正确的邮箱格式");
				return;
			}

		} else if (vId == R.id.information_mobile) {
			if (OtherUtils.isMobileNO(string)) {
				userChange.setMobile(string);
			} else if (OtherUtils.CheckNull(string)) {
				userChange.setMobile("");
			} else {
				toastShow("请输入正确的手机号格式");
				return;
			}

		} else if (vId == R.id.information_microMsg) {
			userChange.setMicroMsg(string);
		} else if (vId == R.id.information_qq) {
			if ("10000".equals(string)) {
				toastShow("这可是官方扣扣！");
				return;
			} else if (OtherUtils.isQQ(string) && (string.length() > 4)) {
				userChange.setQQ(string);
			} else if (OtherUtils.CheckNull(string)) {
				userChange.setQQ("");
			} else {
				toastShow("请输入5-10位数字");
				return;
			}
		} else {
			return;
		}
		String jsonStr = JSON.toJSONString(userChange);
		params.addBodyParameter("content", jsonStr);
		http.send(HttpMethod.POST, url, params, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				if (OtherUtils.CheckNull(responseInfo.result)) {
					return;
				}
				System.out.println("||changeInformation||"
						+ responseInfo.result);
				JsonResult jr = JSON.parseObject(responseInfo.result,
						JsonResult.class);
				if (jr.getResult() == 0) {
					User user = JSON.parseObject(jr.getObject().toString(),
							User.class);
					if (user == null) {
						return;
					}
					user.setIcon1(user.getIcon1());
					db.deleteAll(Selector.from(User.class).where("userId", "=",
							user.getUserId()));
					db.save(user);
					refresh();
				}
				toastShow(jr.getMessage());
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				System.out.println("==================="
						+ error.fillInStackTrace());
			}

		});

	}

	private void informationChange(int vId, int classId) {
		HttpUtils http = new HttpUtils();
		String url = C.HTTP_USER_INFO_UPDATE;
		RequestParams params = new RequestParams();
		url = url.replace("{userId}", user.getUserId() + "");

		User userChange = new User();
		userChange.setUserId(user.getUserId());

		if (vId == R.id.information_class) {
			userChange.setClassId(classId);
		} else {
			return;
		}

		String jsonStr = JSON.toJSONString(userChange);
		params.addBodyParameter("content", jsonStr);
		http.send(HttpMethod.POST, url, params, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				if (OtherUtils.CheckNull(responseInfo.result)) {
					return;
				}
				System.out.println("||changeInformation||class||"
						+ responseInfo.result);
				JsonResult jr = JSON.parseObject(responseInfo.result,
						JsonResult.class);
				if (jr.getResult() == 0) {
					User user = JSON.parseObject(jr.getObject().toString(),
							User.class);
					if (user == null) {
						return;
					}
					db.deleteAll(Selector.from(User.class).where("userId", "=",
							user.getUserId()));
					db.save(user);
					refresh();
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				System.out.println("==================="
						+ error.fillInStackTrace());
			}

		});

	}

	/**
	 * 打开软键盘
	 */
	private void openKeyboard(Handler mHandler, int s) {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}, s);
	}

	/**
	 * 已经改变，隐藏其他控件
	 * 
	 * @param id
	 * @param b
	 */
	private void informationChangeShow(int id, Boolean b) {
		switch (id) {
		case R.id.information_code:
			break;
		case R.id.information_username:
			ifVisible(1, b);
			break;
		case R.id.information_sex:
			ifVisible(2, b);
			break;
		case R.id.information_class:
			ifVisible(3, b);
			break;
		case R.id.information_email:
			ifVisible(4, b);
			break;
		case R.id.information_mobile:
			ifVisible(5, b);
			break;
		case R.id.information_microMsg:
			ifVisible(6, b);
			break;
		case R.id.information_qq:
			ifVisible(7, b);
			break;
		default:
			break;
		}
	}

	private void ifVisible(int m, Boolean b) {
		if (b) {
			for (int i = 0; i < m; i++) {
				lLayout.get(i).setVisibility(View.GONE);
			}
		} else {
			for (int i = 0; i < m; i++) {
				lLayout.get(i).setVisibility(View.VISIBLE);
			}

		}
	}

	private void refresh() {
		user = db.findFirst(User.class);
		bitmapUtils.display(ifIcon, user.getIcon1());
		ifCode.setText(user.getNickName());
		ifUserName.setText(user.getUserName());
		if (user.getSex().equals("female")) {
			ifSex.setText("女");
		} else {
			ifSex.setText("男");
		}
		ifClass.setText(user.getClassId() + "班");
		ifEmail.setText(user.getEmail());
		ifMobile.setText(user.getMobile());
		ifMicroMsg.setText(user.getMicroMsg());
		ifQQ.setText(user.getQQ());
	}

	private String getFileName() {
		Date dd = new Date();
		long time = dd.getTime();
		String fileName = time + "_" + user.getUserId() + ".jpg";
		return fileName;
	}

	/*
	 * 剪切图片
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);

		intent.putExtra("outputFormat", "JPEG");// 图片格式
		intent.putExtra("noFaceDetection", false);// 不取消人脸识别
		intent.putExtra("return-data", true);
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
		startActivityForResult(intent, C.PHOTO_REQUEST_CUT);
	}

	private int UPDATE_HEAD = 1;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == UPDATE_HEAD) {
				HttpUtils http = new HttpUtils();
				String url = C.HTTP_USER_INFO_UPDATE;
				RequestParams params = new RequestParams();

				String path = msg.getData().getString("path");
				bitmapUtils.display(ifIcon, path);
				url = url.replace("{userId}", user.getUserId() + "");

				User user1 = new User();
				user1.setUserId(user.getUserId());
				user1.setIcon1(path);
				String jsonStr = JSON.toJSONString(user1);
				params.addBodyParameter("content", jsonStr);
				http.send(HttpMethod.POST, url, params,
						new RequestCallBack<String>() {

							@Override
							public void onSuccess(
									ResponseInfo<String> responseInfo) {
								if (OtherUtils.CheckNull(responseInfo.result)) {
									return;
								}
								JsonResult jr = JSON.parseObject(
										responseInfo.result, JsonResult.class);
								if (jr.getResult() == 0) {
									User user = JSON.parseObject(jr.getObject()
											.toString(), User.class);
									if (user == null) {
										return;
									}
									db.deleteAll(Selector.from(User.class)
											.where("userId", "=",
													user.getUserId()));
									db.save(user);
									refresh();
								}
							}

							@Override
							public void onFailure(HttpException error,
									String msg) {
								System.out.println("==================="
										+ error.fillInStackTrace());
							}
						});
			}
		}
	};

	@Override
	public void callBack(String str) {
		String path = C.OSS_URL + str;
		Message msg = new Message();
		msg.what = UPDATE_HEAD;
		msg.getData().putString("path", path);
		handler.sendMessage(msg);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == C.PHOTO_REQUEST_GALLERY) {
			// 从相册返回的数据
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				crop(uri);
			}
		} else if (requestCode == C.PHOTO_REQUEST_CUT) {
			// 从剪切图片返回的数据
			if (data != null) {
				String fileName = getFileName();
				Bitmap bitmap = data.getParcelableExtra("data");
				OssManager.getInstance().asyncUpload(bitmap, "head/", fileName,
						this);// /head/
			}
		} else if (requestCode == C.PHOTO_REQUEST_CAMERA) {
			if (resultCode == -1) {
				File temp = new File(Environment.getExternalStorageDirectory()
						+ "/head.jpg");
				crop(Uri.fromFile(temp));// 裁剪图片
			}
		}
	}
}
